let qr = require('qr-image');
let config = require('../config')
let axios = require('axios')

module.exports =  {
  /**
   * 验证token的真实性
   * @return 成功时返回status为ok，失败时返回fail
   */
  async verify_token(ctx, next) {
    try {
        return ctx.body = { status: 'ok', data: {} };
    } catch (e) {
        return ctx.body = { status: 'fail', data: e.message };
    }
  },

  /**
   * 生成一个二维码
   * @return 成功返回生成的二维码，失败返回失败信息
   */
  async make_code(ctx, next) {
    try {
      let url = config.baseUrl + ctx.request.query.url
      let code = qr.image(url, { type: 'png' });
      ctx.set('Content-type', 'image/png');
      ctx.body = code;
    } catch (e) {
      return ctx.body = { status: 'fail', data: e.message };
    }
  },

  /**
   * 通过小程序的code返回openId
   */
  async getOpenId(ctx, next) {
    try {
      let appId = 'wxbb9add1fd0d1f54c', appSecret = '83cd501fc23405bb62e24e2f98d797e6'
      let url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + appId + '&secret=' + appSecret +'&grant_type=authorization_code&js_code=' + ctx.request.body.code
      let result  = await axios.get(url)
      return ctx.body = { status: 'ok', data: result.data };
    } catch (e) {
      return ctx.body = { status: 'fail', data: e.message };
    }
  } 
}